import { User } from '../models/index.js';
import { getTokenFromHeader, verifyToken } from '../utils/jwt.js';

export const authMiddleware = async (ctx, next) => {
  try {
    // 从请求头获取 token
    const token = getTokenFromHeader(ctx);
    if (!token) {
      ctx.throw(401, '未授权');
    }

    // 验证 token
    const decoded = verifyToken(token);
    if (!decoded) {
      ctx.throw(401, '无效的 token');
    }

    // 获取用户信息
    const user = await User.findByPk(decoded.id);
    if (!user) {
      ctx.throw(401, '用户不存在');
    }

    // 检查用户状态
    // if (user.status !== 'active') {
    //   ctx.throw(403, '账号已被禁用');
    // }

    // 将用户信息添加到上下文中
    ctx.state.user = user;
    await next();
  } catch (error) {
    if (error.status === 401 || error.status === 403) {
      throw error;
    }
    ctx.throw(401, '认证失败');
  }
};
